extends RigidBody

# need to be updated manually every frame
var view_rot_y_in_deg: float = 0.0

export(String) var ball_type: String = ""
export(bool) var is_player: bool = false
export(bool) var use_torque: bool = false
export(float) var strength: float = 0.0

# somehow the damping in Godot worked weirdly
export(float) var my_linear_damp: float = 0.0
export(float) var my_angular_damp: float = 0.0

var transform_data: Dictionary = {}
var transform_src_pos: Vector3
var transform_src_velocity: Vector3
var transform_src_angular_velocity: Vector3
var transform_time: float = -1.0

func _ready():
	if is_player:
		var my_camera = get_node_or_null("../LevelTemplate/MyCamera")
		if my_camera != null:
			my_camera.followed_object = self

func _integrate_forces(state):
	if my_linear_damp > 1e-3:
		state.linear_velocity *= exp(-my_linear_damp * state.get_step())
	if my_angular_damp > 1e-3:
		state.angular_velocity *= exp(-my_angular_damp * state.get_step())

	if transform_data.empty():
		return

	if transform_time < 0.0:
		# start transform animation
		transform_time = 0.0
		transform_src_pos = global_transform.origin
		transform_src_velocity = state.linear_velocity
		transform_src_angular_velocity = state.angular_velocity

		is_player = false
		collision_layer = 0
		collision_mask = 0
		gravity_scale = 0.0

	var st: float = state.get_step()
	transform_time += st
	var t: float = clamp(transform_time * 2.0, 0.0, 1.0)
	var old_pos: Vector3 = transform_src_pos + \
		transform_src_velocity * transform_time / (transform_time + 1.0)
	var new_pos: Vector3 = lerp(old_pos, transform_data["target"], t)
	state.linear_velocity = (new_pos - global_transform.origin) / state.get_step()
	state.angular_velocity = (1.0 - t) * transform_src_angular_velocity

# warning-ignore:unused_argument
func _physics_process(delta):
	if not is_player:
		return

	var d: Vector2 = Vector2( \
		Input.get_action_strength("game_right") - Input.get_action_strength("game_left"), \
		Input.get_action_strength("game_up") - Input.get_action_strength("game_down"))

	if d.length_squared() < 1e-3:
		return

	d = d.normalized()

	var i: int = (floor((view_rot_y_in_deg + 765.0) / 90.0) as int) % 4
	var t: Vector3 = Vector3()

	if use_torque:
		match i:
			0:
				t = Vector3(-d.y, 0, -d.x)
			1:
				t = Vector3(-d.x, 0, d.y)
			2:
				t = Vector3(d.y, 0, d.x)
			3:
				t = Vector3(d.x, 0, -d.y)
		add_torque(t * strength)
	else:
		match i:
			0:
				t = Vector3(d.x, 0, -d.y)
			1:
				t = Vector3(-d.y, 0, -d.x)
			2:
				t = Vector3(-d.x, 0, d.y)
			3:
				t = Vector3(d.y, 0, d.x)
		add_central_force(t * strength)
